package com.ding.courier;

import com.ding.common.CreateSocketStrategy;
import com.ding.common.DelayedStreamChannel;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TargetDelayedStreamChannel extends DelayedStreamChannel {

    public TargetDelayedStreamChannel(CreateSocketStrategy createSocketStrategy) {
        super(createSocketStrategy);
    }


    private interface InOutGetter {
        InputStream getInputStream();
        OutputStream getOutputStream();
    }

    private InOutGetter inOutGetter;

    @Override
    public OutputStream getOutputStream() {
        try {
            return inOutGetter.getOutputStream();
        } catch (NullPointerException ignore) {
            Socket socket = getCreateSocketStrategy().create();
            if (socket == null) {
                return getDefaultOutputStream();
            } else {
                inOutGetter = new InOutGetter() {
                    @Override
                    public InputStream getInputStream() {
                        try {
                            return socket.getInputStream();
                        } catch (IOException e) {
                            System.out.println("获取输入流失败");
                            return getDefaultInputStream();
                        }
                    }

                    @Override
                    public OutputStream getOutputStream() {
                        try {
                            return socket.getOutputStream();
                        } catch (IOException e) {
                            System.out.println("获取输出流失败");
                            return getDefaultOutputStream();
                        }
                    }

                };
                getRepeater().startRightToLeft();
                return inOutGetter.getOutputStream();
            }
        }
    }

    @Override
    public InputStream getInputStream() {
        try {
            return inOutGetter.getInputStream();
        } catch (NullPointerException ignore) {
            return getDefaultInputStream();
        }
    }

    @Override
    public void close() {
        super.close();
        System.out.println("关闭目标通信");
        this.inOutGetter = null;
    }
}
